<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('attendance_records', function (Blueprint $table) {
            $table->id();
            $table->timestamps();

            // 员工信息
            $table->unsignedBigInteger('employee_id');
            $table->string('employee_name', 100)->nullable();
            $table->string('employee_number', 50)->nullable();

            // 考勤日期和时间
            $table->date('attendance_date');
            $table->time('scheduled_start_time')->nullable();
            $table->time('scheduled_end_time')->nullable();
            $table->time('actual_start_time')->nullable();
            $table->time('actual_end_time')->nullable();

            // 考勤状态
            $table->string('attendance_status', 20)->default('present');
            $table->decimal('work_hours', 5, 2)->default(0);
            $table->decimal('overtime_hours', 5, 2)->default(0);
            $table->decimal('late_minutes', 5, 2)->default(0);
            $table->decimal('early_leave_minutes', 5, 2)->default(0);

            // 考勤类型
            $table->string('attendance_type', 20)->default('regular'); // regular, overtime, leave, business_trip
            $table->string('shift_type', 20)->nullable(); // morning, afternoon, night, rotating

            // 异常信息
            $table->boolean('is_late')->default(false);
            $table->boolean('is_early_leave')->default(false);
            $table->boolean('is_absent')->default(false);
            $table->boolean('is_leave')->default(false);
            $table->text('exception_reason')->nullable();

            // 补卡信息
            $table->boolean('has_makeup_clock')->default(false);
            $table->integer('makeup_count')->default(0);
            $table->text('makeup_reason')->nullable();

            // 考勤规则
            $table->unsignedBigInteger('attendance_rule_id')->nullable();
            $table->string('rule_name', 100)->nullable();

            // 备注
            $table->text('notes')->nullable();
            $table->string('recorded_by', 100)->nullable();

            // 索引
            $table->index(['employee_id', 'attendance_date']);
            $table->index(['attendance_date', 'attendance_status']);
            $table->index(['attendance_type']);
            $table->index(['shift_type']);
            $table->index(['is_late', 'is_early_leave', 'is_absent']);

            // 外键约束
            $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
            $table->foreign('attendance_rule_id')->references('id')->on('attendance_rules')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('attendance_records');
    }
};
